# Author    : CoffeeChicken
# Date      : 2020-12-02 21:12
# Function  : 演示 拼接url

import re
import os
import requests
import json

headers = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko)'
                  ' Chrome/66.0.3329.0 Mobile Safari/537.36'
}

url = "https://www.iesdouyin.com/web/api/v2/aweme/post/?sec_uid="

user_url = "https://v.douyin.com/JCASaYR/"
while True:
    user_url = input("请输入抖音用户链接: ")
    response = requests.get(user_url)
    # 获取重定向后地址
    redirect_url = response.url
    # print(redirect_url)
    # 正则匹配规则
    reg = ".*sec_uid=(.*?)&"
    # 获取到sec_uid
    sec_uid = re.match(reg, redirect_url).group(1)
    # 拼接最终url
    url += sec_uid

    url += "&count=10000"

    # print(url)

    # 多次遍历
    for _ in range(100):

        result = requests.get(url, headers)
        json_str = result.text
        json_type = json.loads(json_str)
        length = len(json_type["aweme_list"])
        if length != 0:
            print(length)
            for item in json_type["aweme_list"]:
                nickname = item["author"]["nickname"]
                title = item['desc']
                video_url = item["video"]["play_addr"]["url_list"][0]
                # print(video_url)
                est = requests.get(url=video_url, headers=headers)
                if not os.path.exists(nickname):
                    os.mkdir(nickname)
                with open(f'{nickname}/{title}.mp4', 'wb') as f:
                    f.write(est.content)
            break
            # print(length)
    if input("是否继续输入y/n: ") == 'n':
        break
